// pages/submit-order/submit-order.js
var http = require("../../utils/http.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    popupShow: false,
    couponSts: 1,
    couponList: [],
    // 订单入口 0购物车 1立即购买
    orderEntry: "0",
    userAddr: null,
    orderItems: [],
    coupon: {
      totalLength: 0,
      canUseCoupons: [],
      noCanUseCoupons: []
    },
    actualTotal: 0,
    total: 0,
    totalCount: 0,
    transfee: 0,
    reduceAmount: 0,
    remark: "",
    couponIds: [],
    userChangeCoupon: 0, // 用户有没有对优惠券进行改变
    orderReduce: 0,
    choose: true,
    totalScoreAmount: 0,  //积分抵扣金额
    maxUsableScore: 0,  //整个订单可以使用的积分数
    isScorePay: 0,  //用户是否选择积分抵现(0不使用 1使用 默认不使用)
    isChecked: false,  //是否选择会员积分抵现
    isProhibit: false,  //（积分抵现）checkbox是否禁止
    totalLevelAmount: 0,  //等级抵扣金额
    freeTransfee: 0,  //用户等级免运费金额
    totalTransfee: 0, //运费
    shopCartItemDiscounts: {},

    userUseScore: '', // 用于抵扣的金额数量
    scorePopPlaceholder:'', // 积分弹窗输入框占位符
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      orderEntry: options.orderEntry,
    });
    this.getUserScore()
  },
  
  // 会员积分抵现选择
  useMemberPoints: function () {
    this.data.isChecked = !this.data.isChecked
    if (this.data.maxUsableScore > 0) {  // maxUsableScore 整个订单可以使用的积分数
      this.setData({
        isScorePay: this.data.isChecked? 1:0,
        userUseScore: this.data.isChecked? this.data.userUseScore : 0
      })
      this.loadOrderData()
    }
  },
  /**
   * 积分抵扣输入框
   */
  handleScoreInput(e){
    var maxScore = 0
    if (this.data.maxUsableScore > this.data.accountScore) {
      maxScore = this.data.accountScore
    } else {
      maxScore = this.data.maxUsableScore
    }
    this.setData({
      userUseScore: e.detail.value>0 ? e.detail.value > maxScore ? maxScore : e.detail.value: ''
    })
  },
  /**
   * 修改积分确定弹窗
   */
  confirmScore(){
    this.loadOrderData()
    this.closePopup()
  },

  //加载订单数据
  loadOrderData: function() {
    var addrId = 0;
    if (this.data.userAddr != null) {
      addrId = this.data.userAddr.addrId;
    }
    wx.showLoading({
      mask: true
    });
    var params = {
      url: "/p/order/confirm",
      method: "POST",
      data: {
        addrId: addrId,
        orderItem: this.data.orderEntry === "1" ? JSON.parse(wx.getStorageSync("orderItem")) : undefined,
        basketIds: this.data.orderEntry === "0" ? JSON.parse(wx.getStorageSync("basketIds")) : undefined,
        couponIds: this.data.couponIds,
        userChangeCoupon: this.data.userChangeCoupon,
        isScorePay: this.data.isScorePay,
        userUseScore: this.data.userUseScore?this.data.userUseScore:0 ,
      },
      callBack: res => {
        wx.hideLoading();
        let orderItems = [];

        res.shopCartOrders[0].shopCartItemDiscounts.forEach(itemDiscount => {
          orderItems = orderItems.concat(itemDiscount.shopCartItems)
        })
        if (res.shopCartOrders[0].coupons) {
          let canUseCoupons = []
          let unCanUseCoupons = []
          res.shopCartOrders[0].coupons.forEach(coupon => {
            if (coupon.canUse) {
              canUseCoupons.push(coupon)
            } else {
              unCanUseCoupons.push(coupon)
            }
          })
          this.setData({
            coupons: {
              totalLength: res.shopCartOrders[0].coupons.length,
              canUseCoupons: canUseCoupons,
              unCanUseCoupons: unCanUseCoupons
            }
          })
        }

        this.setData({
          orderItems: orderItems,
          actualTotal: res.actualTotal,
          total: res.total,
          totalCount: res.totalCount,
          userAddr: res.userAddr,
          transfee: res.shopCartOrders[0].transfee,
          shopReduce: res.shopCartOrders[0].shopReduce,
          totalLevelAmount: res.totalLevelAmount,
          freeTransfee: res.freeTransfee,
          isScorePay: res.isScorePay,
          totalScoreAmount: res.totalScoreAmount,
          maxUsableScore: res.maxUsableScore,
          scorePrice: res.scorePrice,
          shopCartItemDiscounts: res.shopCartOrders[0].shopCartItemDiscounts,
          totalTransfee: res.totalTransfee,  //运费
          couponReduce: res.shopCartOrders[0].couponReduce, // 优惠券减免金额
          scorePlaceholder: `使用${res.totalUsableScore}积分抵扣${res.totalScoreAmount}元`,
          scorePopPlaceholder: `剩余积分${this.data.accountScore}，此订单最多可用${res.maxUsableScore}`
        });
      },
      errCallBack: res => {
        wx.hideLoading();
      }
    };
    http.request(params);
  },

  /**
   * 提交订单
   */
  toPay: function() {
    if (!this.data.userAddr) {
      wx.showToast({
        title: '请选择地址',
        icon: "none"
      })
      return;
    }

    this.submitOrder();
  },


  submitOrder: function() {
    wx.showLoading({
      mask: true
    });
    var params = {
      url: "/p/order/submit",
      method: "POST",
      data: {
        orderShopParam: [{
          remarks: this.data.remark,
          shopId: 1
        }]
      },
      callBack: res => {
        wx.hideLoading();
        this.calWeixinPay(res.orderNumbers);
      }
    };
    http.request(params);
  },

  /**
   * 唤起微信支付
   */
  calWeixinPay: function(orderNumbers) {
    wx.showLoading({
      mask: true
    });
    var params = {
      url: "/p/order/pay",
      method: "POST",
      data: {
        payType: 1,
        orderNumbers: orderNumbers
      },
      callBack: function(res) {
        wx.hideLoading();
        console.log('要支付的价格:',this.data.actualTotal)
        if (this.data.actualTotal == 0) {
          wx.navigateTo({
            url: '/pages/pay-result/pay-result?sts=1&orderNumbers=' + orderNumbers + "&orderType=" + this.data.orderType,
          })
        } else {
          wx.requestPayment({
            timeStamp: res.timeStamp,
            nonceStr: res.nonceStr,
            package: res.packageValue,
            signType: res.signType,
            paySign: res.paySign,
            success: e => {
              // console.log("支付成功");
              wx.redirectTo({
                url: `/pages/pay-result/pay-result?sts=1&orderNumbers=${orderNumbers}&orderType=${this.data.orderType}`,
              })
            },
            fail: err => {
              wx.redirectTo({
                url: `/pages/pay-result/pay-result?sts=0&orderNumbers=${orderNumbers}&orderType=${this.data.orderType}`,
              })
            }
          })
        }

      }
    };
    http.request(params);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    if (currPage.data.selAddress == "yes") {
      this.setData({ //将携带的参数赋值
        userAddr: currPage.data.item
      });
    }
    //获取订单数据
    this.loadOrderData();
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  changeCouponSts: function(e) {
    this.setData({
      couponSts: e.currentTarget.dataset.sts
    });
  },

  showCouponPopup: function() {
    this.setData({
      popupShow: true
    });
  },

  closePopup: function() {
    this.setData({
      popupShow: false,
      showScorePop: false
    });
  },

  /**
   * 去地址页面
   */
  toAddrListPage: function() {
    wx.navigateTo({
      url: '/pages/delivery-address/delivery-address?order=0',
    })
  },
  /**
   * 确定选择好的优惠券
   */
  choosedCoupon: function() {
    var couponIds = []
    var canUseCoupons = this.data.coupons.canUseCoupons;
    for (var canUseCouponIndex in canUseCoupons) {
      if (canUseCoupons[canUseCouponIndex].choose) {
        // 找到所有被选中的优惠券
        couponIds.push(canUseCoupons[canUseCouponIndex].couponId)
      }
    }
    this.setData({
      couponIds: couponIds
    });
    this.loadOrderData();

    this.setData({
      popupShow: false
    });
  },

  /**-
   * 优惠券子组件发过来
   */
  checkCoupon: function(e) {
    // 优惠券单选操作
    var coupons = this.data.coupons
    var canUseCoupons = coupons.canUseCoupons;
    console.log(e.detail.couponId)
    for (var canUseCouponIndex in canUseCoupons) {
      console.log(canUseCouponIndex)
      if (e.detail.couponId === canUseCoupons[canUseCouponIndex].couponId) {
        console.log(canUseCoupons[canUseCouponIndex].couponId)
        // 选中了变成没有选中
        if (canUseCoupons[canUseCouponIndex].choose) {
          canUseCoupons[canUseCouponIndex].choose = false
        } else {
          console.log(canUseCoupons[canUseCouponIndex].choose)
          // 没有选中则变成选中，其他被选中的变成没有选中
          for (var newCanUseCoupons in canUseCoupons) {
            console.log(canUseCoupons[newCanUseCoupons].choose = canUseCoupons[canUseCouponIndex].couponId === canUseCoupons[newCanUseCoupons].couponId)
            canUseCoupons[newCanUseCoupons].choose = canUseCoupons[canUseCouponIndex].couponId === canUseCoupons[newCanUseCoupons].couponId
          }
        }
        this.setData({
          coupons: coupons,
          userChangeCoupon: 1
        });
        break;
      }
    }
  },


  /**
   * 输入备注
   */
  onRemarkIpt:function(e){
    this.setData({
      remark: e.detail.value
    });
  },
  /**
   * 积分输入弹窗显示
   */
  handleScorePop(){
    this.setData({
      userUseScore: '',
      showScorePop: true
    })
  },

    /**
   * 获取用户可用积分
   */
  getUserScore(){
    var params = {
      url:'/p/user/userInfo',
      method:'GET',
      callBack: res => {
        this.setData({
          accountScore : res.score
        })
      }
    }
    http.request(params)
  },
})
